//
//  TalksTableViewController.m
//  ENTBoostChat
//
//  Created by zhong zf on 14-8-2.
//  Copyright (c) 2014年 EB. All rights reserved.
//

#import "TalksTableViewController.h"
#import "TalkViewController.h"
#import "MainViewController.h"
#import "ENTBoost.h"
#import "SeedUtility.h"
#import "BlockUtility.h"
#import "TalksCell.h"
#import "BDDynamicTreeNode.h"

static NSString* TalkControllerIdentifier = @"talkController_ID"; //聊天界面资源编号

@interface TalksTableViewController ()

@end

@implementation TalksTableViewController
{
    UIStoryboard* _talkStoryobard;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.p2pTalkViewControllesrs = [NSMutableDictionary dictionary];
        self.groupTalkViewControllers = [NSMutableDictionary dictionary];
        self.talkIds = [NSMutableArray array];
        
        _talkStoryobard = [UIStoryboard storyboardWithName:@"Talk" bundle:nil];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //查询获取对话归类
    ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
    NSArray* talks = [ebKit talks];
    
    __weak typeof(self) safeSelf = self;
    [talks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        EBTalk* talk = obj;
        
        //获取该对话归类下聊天记录数量
        NSUInteger msgCount = [ebKit countOfMessagesWithTalkId:talk.talkId andBeginTime:nil endTime:nil];
        if(!msgCount) {
            NSLog(@"no message, miss to create TalkViewController,  talkId = %@", talk.talkId);
            return;
        }
        
        BOOL bAdded = [safeSelf addTalkId:talk.talkId append:YES];
        
        //如果成功加入，就生成对应界面
        if(bAdded) {
            TalkViewController* tvc = [_talkStoryobard instantiateViewControllerWithIdentifier:TalkControllerIdentifier];
            tvc.talksController = safeSelf;
            tvc.talkId = talk.talkId;

            //加入界面缓存
            if (talk.isGroup) {
                tvc.depCode = talk.depCode;
                tvc.depName = talk.depName;
                
                NSNumber* key = [NSNumber numberWithUnsignedLongLong:talk.depCode];
                safeSelf.groupTalkViewControllers[key] = tvc;
            } else {
                tvc.otherUid = talk.otherUid;
                tvc.otherAccount = talk.otherAccount;
                tvc.otherUserName = talk.otherUserName;
                
                NSNumber* key = [NSNumber numberWithUnsignedLongLong:talk.otherUid];
                safeSelf.p2pTalkViewControllesrs[key] = tvc;
            }
        }
    }];
    
    //注册接收通知：显示对话界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTalk:) name:EBCHAT_NOTIFICATION_RELATIONSHIP_DIDSELECT object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    //移除接收通知的注册
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EBCHAT_NOTIFICATION_RELATIONSHIP_DIDSELECT object:nil];
}

//处理接收显示聊天界面的通知
- (void)showTalk:(NSNotification*)notif
{
    if(notif.userInfo) {
        ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
        __weak typeof(self) safeSelf = self;
        
        BDDynamicTreeNode* node = notif.userInfo[@"node"];
        RELATIONSHIP_TYPE type = ((NSNumber*)node.data[@"type"]).shortValue;
        __block uint64_t otherUid = 0;
        NSString* otherAccount;
        NSString* otherUserName;
        uint64_t depCode = 0;
        
        switch (type) {
            case RELATIONSHIP_TYPE_MYDEPARTMENT: //我的部门
            case RELATIONSHIP_TYPE_ENTGROUP: //部门
            case RELATIONSHIP_TYPE_PERSONALGROUP: //个人群组
            {
                EBGroupInfo* groupInfo = node.data[@"groupInfo"];
                depCode = groupInfo.depCode;
            }
                break;
            case RELATIONSHIP_TYPE_MEMBER: //部门或群组成员
            {
                EBMemberInfo* memberInfo = node.data[@"memberInfo"];
                otherUid = memberInfo.uid;
                otherAccount = memberInfo.empAccount;
                otherUserName = memberInfo.userName;
            }
                break;
            case RELATIONSHIP_TYPE_CONTACT: //通讯录中的联系人
            {
                EBContactInfo* contactInfo = node.data[@"contactInfo"];
                dispatch_semaphore_t sem = dispatch_semaphore_create(0);
                [ebKit queryUidWithAccount:contactInfo.contact onCompletion:^(uint64_t uid) {
                    otherUid = uid;
                    dispatch_semaphore_signal(sem);
                } onFailure:^(NSError *error) {
                    NSLog(@"查询联系人失败, code = %i, msg = %@", error.code, error.localizedDescription);
                    dispatch_semaphore_signal(sem);
                }];
                dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 5.0f * NSEC_PER_SEC)); //最长等待5秒
                otherAccount = contactInfo.contact;
                otherUserName = contactInfo.name;
            }
            default:
                break;
        }
        
        if (!otherUid && !depCode) {
            NSLog(@"uid 和 depCode都等于0，没有对话目标");
            return;
        }
        
        if (otherUid == ebKit.accountInfo.uid) {
            NSLog(@"不能与自己进行对话");
            return;
        }
        
        [BlockUtility performBlockInMainQueue:^{
            [self createOrUpdateTalkViewControllerWithOtherUid:otherUid otherAccount:otherAccount otherUserName:otherUserName depCode:depCode noMessageShow:YES onCompletion:^(TalkViewController *tvc) {
                [BlockUtility performBlockInMainQueue:^{
                    //尝试让会话进入就绪状态
                    BOOL waittingResult, result;
                    [tvc detectAndLaunchCallWithWaitting:&waittingResult result:&result];
                    
                    //切换至聊天页
                    [safeSelf.tabBarController setSelectedViewController:safeSelf.parentViewController];
                    
                    //如果在导航视图中该TalkView聊天界面没有显示，就使它显示
                    if(![[safeSelf.navigationController topViewController] isEqual:tvc]) {
                        [safeSelf.navigationController popToRootViewControllerAnimated:NO];
                        
                        safeSelf.hidesBottomBarWhenPushed = YES;
                        [safeSelf.navigationController pushViewController:tvc animated:YES];
                        safeSelf.hidesBottomBarWhenPushed = NO;
                    }
                }];
            } onFailure:^(NSError *error) {
                
            }];
            
            
        }];
    }
    
}


/**把talkId加入到显示队列中
 * @param talkId 对话归类编号
 * @param append 是否追加在最后，YES=追加在最后，NO=插入在第一位置
 * @return 是否成功加入, 如有重复将不能加入
 */
- (BOOL)addTalkId:(NSString*)talkId append:(BOOL)append
{
    __block BOOL isEqual = NO;
    [self.talkIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([talkId isEqualToString:(NSString*)obj]) {
            isEqual = YES;
            *stop = TRUE;
        }
    }];
    
    if(!isEqual) {
        if (append)
            [self.talkIds addObject:talkId];
        else
            [self.talkIds insertObject:talkId atIndex:0];
       
        return YES;
    }
    
    return NO;
}

/**创建或更新聊天界面对象
 *
 */
- (void)createOrUpdateTalkViewControllerWithOtherUid:(uint64_t)otherUid otherAccount:(NSString*)otherAccount otherUserName:(NSString*)otherUserName depCode:(uint64_t)depCode noMessageShow:(BOOL)forceShow onCompletion:(void(^)(TalkViewController* tvc))completionBlock onFailure:(void(^)(NSError *error))failureBlock
{
    ENTBoostKit* ebKit = [ENTBoostKit sharedToolKit];
    __block TalkViewController* tvc;
    __block EBTalk* talk;
    __weak typeof(self)safeSelf = self;
    
    if(depCode) { //群组会话
        void(^block)(void) = ^{
            //非强制显示时，需检查是否存在聊天记录才显示界面
            if(!forceShow) {
                //获取该对话归类下聊天记录数量
                NSUInteger msgCount = [ebKit countOfMessagesWithTalkId:talk.talkId andBeginTime:nil endTime:nil];
                if(!msgCount) {
                    NSLog(@"no message, miss to create TalkViewController,  talkId = %@", talk.talkId);
                    return;
                }
            }
            
            //查找已有会话
            NSNumber* key = [NSNumber numberWithUnsignedLongLong:depCode];
            tvc = safeSelf.groupTalkViewControllers[key];
            
            //插入到显示队列最前面
            BOOL bAdded = [safeSelf addTalkId:talk.talkId append:NO];
            //如果成功加入，就生成对应界面
            if(bAdded) {
                if(!tvc) { //如果不存在就新产生一个
                    tvc = [_talkStoryobard instantiateViewControllerWithIdentifier:TalkControllerIdentifier];
                    tvc.talksController = safeSelf;
                    tvc.talkId = talk.talkId;
                    tvc.depCode = talk.depCode;
                    
                    safeSelf.groupTalkViewControllers[key] = tvc;
                }
                //更新信息
                tvc.depName = talk.depName;
            }
            
            [safeSelf.tableView reloadData]; //刷新表视图
            
            if (completionBlock) completionBlock(tvc);
        };
        
        //获取对应的对话归类
        talk = [ebKit talkWithDepCode:depCode];
        if (!talk) {
            [ebKit insertOrUpdateTalkWithDepCode:depCode onCompletion:^(EBTalk *newTalk) {
                talk = newTalk;
                [BlockUtility performBlockInMainQueue:block];
            } onFailure:^(NSError *error) {
                NSLog(@"createOrUpdateTalkViewControllerWithOtherUid error, code = %i, msg = %@", error.code, error.localizedDescription);
                if (failureBlock) failureBlock(error);
            }];
        } else {
            [BlockUtility performBlockInMainQueue:block];
        }
    } else { //一对一会话
        void(^block)(void) = ^{
            //非强制显示时，需检查是否存在聊天记录才显示界面
            if(!forceShow) {
                //获取该对话归类下聊天记录数量
                NSUInteger msgCount = [ebKit countOfMessagesWithTalkId:talk.talkId andBeginTime:nil endTime:nil];
                if(!msgCount) {
                    NSLog(@"no message, miss to create TalkViewController,  talkId = %@", talk.talkId);
                    return;
                }
            }
            
            //查找已有会话
            NSNumber* key = [NSNumber numberWithUnsignedLongLong:otherUid];
            tvc = safeSelf.p2pTalkViewControllesrs[key];
            
            //插入到显示队列最前面
            BOOL bAdded = [safeSelf addTalkId:talk.talkId append:NO];
            //如果成功加入，就生成对应界面
            if(bAdded) {
                if(!tvc) { //如果不存在就新产生一个
                    tvc = [_talkStoryobard instantiateViewControllerWithIdentifier:TalkControllerIdentifier];
                    tvc.talksController = safeSelf;
                    tvc.talkId = talk.talkId;
                    tvc.otherUid = otherUid;
                    tvc.otherAccount = talk.otherAccount;
                    
                    safeSelf.p2pTalkViewControllesrs[key] = tvc;
                }
                //更新信息
                tvc.otherUserName = talk.otherUserName;
            }
            
            [safeSelf.tableView reloadData]; //刷新表视图
            
            if (completionBlock) completionBlock(tvc);
        };
        
        //获取对应的对话归类
        talk = [ebKit talkWithUid:otherUid];
        if (!talk) {
            [ebKit insertOrUpdateTalkWithUid:otherUid otherAccount:otherAccount otherUserName:otherUserName onCompletion:^(EBTalk *newTalk) {
                talk = newTalk;
                [BlockUtility performBlockInMainQueue:block];
            } onFailure:^(NSError *error) {
                NSLog(@"createOrUpdateTalkViewControllerWithOtherUid error, code = %i, msg = %@", error.code, error.localizedDescription);
                if (failureBlock) failureBlock(error);
            }];
        } else {
            [BlockUtility performBlockInMainQueue:block];
        }
        
    }
}

- (void)dispatchReceviedMessage:(EBMessage*)message
{
    __weak typeof(self) safeSelf = self;
    
    EBCallInfo* callInfo = [[ENTBoostKit sharedToolKit] callInfoWithCallId:message.callId];
    uint64_t otherUid = callInfo.isGroupCall?0:callInfo.onePerson.uid;
    NSString* otherAccount = callInfo.isGroupCall?nil:callInfo.onePerson.account;
    NSString* otherUserName = callInfo.isGroupCall?nil:callInfo.onePerson.vCard.name;
    
    [self createOrUpdateTalkViewControllerWithOtherUid:otherUid otherAccount:otherAccount otherUserName:otherUserName depCode:callInfo.depCode noMessageShow:NO onCompletion:^(TalkViewController *tvc) {
        //创建或更新聊天界面对象
        [BlockUtility performBlockInMainQueue:^{
            //在聊天界面中显示信息
            BOOL bAdded = [tvc addMessages:@[message] append:YES];
            
            //消息成功添加入tvc界面后，调整Talks表视图显示顺序
            if(bAdded) {
                [tvc scrollToBottom:YES]; //滚动到最后一行
                [safeSelf adjustTableViewWithTalkId:tvc.talkId];
            }
        }];
    } onFailure:^(NSError *error) {
        
    }];
    
    //更新应用图标上数字
    NSUInteger count = [[ENTBoostKit sharedToolKit] countOfUnreadMessages];
    [UIApplication sharedApplication].applicationIconBadgeNumber = count>99?99:count;
}

- (void)adjustTableViewWithTalkId:(NSString*)talkId
{
    //检查当前talk是否在显示队列的第一位,如不是就调整至第一位置
    __block NSInteger foundIdx = -1;
    [self.talkIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([talkId isEqualToString:(NSString*)obj]) {
            foundIdx = idx;
            *stop = TRUE;
        }
    }];
    
    if (foundIdx > 0) { //已找到且不在第一位置
        [self.talkIds removeObjectAtIndex:foundIdx]; //从旧位置删除
        [self.talkIds insertObject:talkId atIndex:0]; //插入到第一位置
        [self.tableView reloadData];
    } else if (foundIdx < 0) { //不存在
        [self.talkIds insertObject:talkId atIndex:0]; //插入到第一位置
        [self.tableView reloadData];
    }
}

- (void)handleCall:(const EBCallInfo*)callInfo callActionType:(CALL_ACTION_TYPE)callActionType
{
    switch (callActionType) {
        case CALL_ACTION_TYPE_CONNECTED: //会话就绪
        {
            uint64_t otherUid = callInfo.isGroupCall?0:callInfo.onePerson.uid;
            NSString* otherAccount = callInfo.isGroupCall?nil:callInfo.onePerson.account;
            NSString* otherUserName = callInfo.isGroupCall?nil:callInfo.onePerson.vCard.name;
            
            [self createOrUpdateTalkViewControllerWithOtherUid:otherUid otherAccount:otherAccount otherUserName:otherUserName depCode:callInfo.depCode noMessageShow:NO onCompletion:^(TalkViewController *tvc) {
            } onFailure:^(NSError *error) {
            }];
        }
            break;
        case CALL_ACTION_TYPE_BUSY: //对方忙，没有响应邀请
        {
            
            
        }
            break;
        case CALL_ACTION_TYPE_REJECT: //对方拒绝邀请
        {
            
        }
            break;
    }
}

- (void)handleCallHangup:(const EBCallInfo*)callInfo
{
    
}

- (void)handleCallAlerting:(const EBCallInfo*)callInfo toUid:(uint64_t)toUid
{
    
}

- (void)handleCallIncoming:(const EBCallInfo *)callInfo fromUid:(uint64_t)fromUid fromAccount:(NSString *)fromAccount vCard:(EBVCard *)vCard clientAddress:(NSString *)clientAddress
{
    NSLog(@"handleCallIncoming callId = %llu, fromUid = %llu, fromAccount = %@, userName = %@, clientAddress = %@", callInfo.callId, fromUid, fromAccount, vCard.name, clientAddress);
    //自动应答(待定)
    [[ENTBoostKit sharedToolKit] ackTheCall:callInfo.callId accept:YES onCompletion:^{
        NSLog(@"应答邀请成功, callId = %llu", callInfo.callId);
        //[self createOrUpdateTalkViewControllerWithCallInfo:callInfo]; //创建或更新聊天界面对象
    } failure:^(NSError *error) {
        NSLog(@"应答邀请失败, callId = %llu", callInfo.callId);
    }];
}

- (void)refreshEmotions:(NSArray *)expressions headPhotos:(NSArray *)headPhotos
{
    [BlockUtility performBlockInMainQueue:^{
        [self.p2pTalkViewControllesrs enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            TalkViewController* tvc = obj;
            [tvc refreshStampInputView];
        }];
        
        [self.groupTalkViewControllers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            TalkViewController* tvc = obj;
            [tvc refreshStampInputView];
        }];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.talkIds.count;
}

//查询已缓存的TalkViewController
- (TalkViewController*)talkViewControllerWithTalkId:(NSString*)talkId
{
    __block TalkViewController* tvc;
    [self.p2pTalkViewControllesrs enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        TalkViewController* tmpTvc = obj;
        if([tmpTvc.talkId isEqualToString:talkId]) {
            tvc = obj;
            *stop = true;
        }
    }];
    
    if(!tvc)
        [self.groupTalkViewControllers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            TalkViewController* tmpTvc = obj;
            if([tmpTvc.talkId isEqualToString:talkId]) {
                tvc = obj;
                *stop = true;
            }
        }];
    
    return tvc;
}

//更新显示未读提示
- (void)updateBadgeIncell:(TalksCell*)cell forTalkId:(NSString*)talkId
{
    //设置未读消息提示
    NSUInteger countOfUnreadMsg = [[ENTBoostKit sharedToolKit] countOfUnreadMessagesWithTBTalkId:talkId];
    cell.badgeString = countOfUnreadMsg>99?@"99+":(!countOfUnreadMsg?nil:[NSString stringWithFormat:@"%i", countOfUnreadMsg]);
    cell.badgeColor = [UIColor colorWithRed:0.6 green:0.0 blue:0.0 alpha:1.000];
    //cell.badgeColor = [UIColor colorWithRed:0.197 green:0.592 blue:0.219 alpha:1.000];
    cell.badge.radius = 9;
    
    //设置talksView的badge
//    UIViewController* viewController = (UIViewController*)self.tabBarController.viewControllers[0];
//    NSInteger badgeValue = 0;
//    NSString* originBadgeValue = viewController.tabBarItem.badgeValue;
//    if (originBadgeValue && originBadgeValue.length>0) {
//        badgeValue += originBadgeValue.integerValue;
//    }
//    badgeValue += countOfUnreadMsg;
//    
//    NSString* badgeString;
//    if (badgeValue >0)
//        badgeString = [NSString stringWithFormat:@"%i", badgeValue];
//
//    viewController.tabBarItem.badgeValue = countOfUnreadMsg?@"1":nil;
}

- (void)updateBadgeWithTalkId:(NSString*)talkId
{
    __block TalksCell* cell;
    NSArray* cells = [self.tableView visibleCells];
    [cells enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TalksCell* tmpCell = obj;
        if ([tmpCell.talkId isEqualToString:talkId]) {
            cell = tmpCell;
            *stop = YES;
        }
    }];
    
    if (cell) {
        [self updateBadgeIncell:cell forTalkId:talkId];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"talkCell";
    TalksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    //通过行索引获取显示队列中的talkId
    NSString* talkId = [self.talkIds objectAtIndex:indexPath.row];
    
    cell.talkId = talkId;
    [self updateBadgeIncell:cell forTalkId:talkId];
    
    TalkViewController* tvc = [self talkViewControllerWithTalkId:talkId];
    
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:11.0];
    
    if(tvc.depCode) { //群组聊天
        cell.textLabel.text = tvc.depName;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"DepCode[%llu]", tvc.depCode];
    } else { //一对一聊天
        cell.textLabel.text = tvc.otherUserName;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Uid[%llu] 账号[%@]", tvc.otherUid, tvc.otherAccount];
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* talkId = [self.talkIds objectAtIndex:indexPath.row];
    TalkViewController* tvc = [self talkViewControllerWithTalkId:talkId];
    
    //尝试让会话进入就绪状态
    BOOL waittingResult, result;
    [tvc detectAndLaunchCallWithWaitting:&waittingResult result:&result];
    
    //进入聊天界面
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tvc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

@end
